package com.reggie.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.entity.Employee;
import com.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Objects;


/**
 * 员工信息(Employee)表控制层
 *
 * @author makejava
 * @since 2022-08-29 12:11:39
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    /**
     * 服务对象
     */
    @Resource
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        // md5 贼喊捉贼
        String password = employee.getPassword();
        password = DigestUtil.md5Hex(password.getBytes(StandardCharsets.UTF_8));
        // 查数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(queryWrapper, true);
        if (Objects.isNull(one)) {
            return R.error("登陆失败");
        }
        if (!one.getPassword().contentEquals(password)) {
            return R.error("密码错误");
        }
        // 查看员工状态
        if (0 == one.getStatus()) {
            return R.error("账号冻结");
        }
        request.getSession().setAttribute("employee", one.getId());
        return R.success(one);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        // 清理session
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        log.info("新增员工：{}", employee.toString());
        // 默认初始密码
        employee.setPassword(DigestUtil.md5Hex("123456", StandardCharsets.UTF_8));
        // employee.setCreateTime(LocalDateTime.now());
        // employee.setUpdateTime(LocalDateTime.now());
        // Long empId = (Long) request.getSession().getAttribute("employee");
        // employee.setCreateUser(empId);
        // employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam("page") int page, @RequestParam("pageSize") int pageSize, String name) {
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        log.info("page = {} , pageSize = {} , name = {}", page, pageSize, name);
        // 构造分页构造器
        Page<Employee> pageInfo = new Page(page, pageSize);
        // 构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = Wrappers.lambdaQuery(Employee.class);
        queryWrapper.like(StrUtil.isNotBlank(name), Employee::getName, name);
        // 添加排序
        queryWrapper.orderByDesc(Employee::getCreateTime);
        // 执行查询
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        log.info("根据id查询员工信息：{}", id);
        Employee employee = employeeService.getById(id);
        if (ObjectUtil.isNotNull(employee)) {
            return R.success(employee);
        }
        return R.error("无此用户");
    }

    /**
     * 通用修改
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpServletRequest servletRequest) {
        log.info("当前线程ID：{}", Thread.currentThread().getId());
        log.info(employee.toString());
        // employee.setUpdateTime(LocalDateTime.now());
        // Long currUserId = (Long) servletRequest.getSession().getAttribute("employee");
        // employee.setUpdateUser(currUserId);
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }
}

